// 导入axios对象
import request from '@/utils/request.js'

// 导入store(Vuex)，可以判断用户是否登录系统 store.state.user.token?'登录':'未登录'
import store from '@/store/index.js'

// 本地持久储存频道设置的key(游客 和 登录用户 分别设置)
const CHANNEL_KET_TRAVEL = 'hm-channel-travel' // 游客KEY
const CHANNEL_KET_VIP = 'hm-channel-vip' // 登录用户KEY

// 删除频道
export async function apiChannelDel (channel) {
    // 判断用户是否登录，获得对象key
    const key = store.state.user.token? CHANNEL_KET_VIP:CHANNEL_KET_TRAVEL
    const cacheChannels = JSON.parse(localStorage.getItem(key))
    const tmpChannels = cacheChannels.filter(item => {
        return channel.id !== item.id
    })
    localStorage.setItem(key, JSON.stringify(tmpChannels))
    return null
}

// 添加频道
export async function apiChannelAdd (channel) {
    // 判断用户是否登录，登录对象key
    const key = store.state.user.token ? CHANNEL_KET_VIP : CHANNEL_KET_TRAVEL

    const cacheChannels = JSON.parse(localStorage.getItem(key))
    cacheChannels.push(channel)
    localStorage.setItem(key,JSON.stringify(cacheChannels))
    return null
}

// 获得全部频道
export async function apiChannelList () {
    const key = store.state.user.token ? CHANNEL_KET_VIP : CHANNEL_KET_TRAVEL
    const cacheChannels = localStorage.getItem(key)

    if (cacheChannels) {
        return { channels: JSON.parse(cacheChannels) }
    } else {
        const rst = await request({
            url: '/app/v1_0/user/channels',
            method: 'get'
        })
        localStorage.setItem(key,JSON.stringify(rst.channels))
        return rst
    }
}

// 获取用户的频道列表数据
export function apiChannelAll () {
    return request({
        url: '/app/v1_0/channels',
        method: 'get'
    })
}